package com.isa.util;

import java.io.IOException;
import java.util.logging.Filter;
import java.util.logging.LogRecord;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class CharacterEncodingFilter implements javax.servlet.Filter {
	
	
	private String characterEncoding;    //编码方式，配置在web.xml里
	private boolean enabled;      //是否启用该Filter，配置在web.xml里
	
	public void destroy() {
		characterEncoding = null;
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		if(enabled || characterEncoding!=null){    //如果启用该Filter
			arg0.setCharacterEncoding(characterEncoding);
			arg1.setCharacterEncoding(characterEncoding);
		}
		arg2.doFilter(arg0, arg1);    //doFilter,执行下一个Servlet或者Filter
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		//初始化时加载参数
		characterEncoding = arg0.getInitParameter("characterEncoding");
		enabled = "true".equals(arg0.getInitParameter("enabled").trim());
				
	}

}
